#include "Cylinder.h"

Cylinder::Cylinder(float H, float R, int nSeg) :
    height(H),
    radius(R),
    nSeg(nSeg)
{
    float inc = 2.0 * M_PI / (float)nSeg;

    for(int i=0; i <= nSeg; ++i)
    {
        Point3f p( radius * cos(i * inc), radius * sin(i * inc), 0.0);
        vertices.push_back(p);
    }
    for(int i=0; i <= nSeg; ++i)
    {
        Point3f p = vertices[i];
        p.z = height;

        vertices.push_back(p);
    }
    for(int i=0; i <= nSeg; ++i)
    {
        Vector3f n( cos(i * inc), sin(i * inc), 0.0);
        normals.push_back(n);
    }
}

void Cylinder::draw()
{
    glColor3f(1.0, 0.0, 0.0);

    glBegin(GL_TRIANGLE_FAN);
        glNormal3f(0.0, 0.0, -1.0);
        glVertex3f(0.0, 0.0, 0.0);
        for(int i=nSeg; i >= 0; --i)
            glVertex3fv(&vertices[i].x);
    glEnd();

    glBegin(GL_TRIANGLE_FAN);
        glNormal3f(0.0, 0.0, 1.0);
        glVertex3f(0.0, 0.0, height);
        for(int i=nSeg+1; i < (int)vertices.size(); ++i)
            glVertex3fv(&vertices[i].x);
    glEnd();

    glBegin(GL_TRIANGLE_STRIP);
        for(int i=0; i <= nSeg; ++i)
        {
            glNormal3fv(&normals[i].x);
            glVertex3fv(&vertices[i + nSeg + 1].x);
            glVertex3fv(&vertices[i].x);
        }
    glEnd();
}
